﻿// See https://aka.ms/new-console-template for more information
using System.Text;
using TouchSocket.Core;
using TouchSocket.Sockets;

Console.WriteLine("Hello, World!");

RunClientForReceived();

Console.ReadKey();

/// <summary>
/// 以Received异步委托接收数据
/// </summary>
static void RunClientForReceived()
{
    var client = new TcpClient();
    client.Connected = (client, e) => { return EasyTask.CompletedTask; };//成功连接到服务器
    client.Disconnected = (client, e) => { return EasyTask.CompletedTask; };//从服务器断开连接，当连接不成功时不会触发。
    client.Received = (client, e) =>
    {
        //从服务器收到信息
        var mes = Encoding.UTF8.GetString(e.ByteBlock.Buffer, 0, e.ByteBlock.Len);
        client.Logger.Info($"客户端接收到信息：{mes}");
        return EasyTask.CompletedTask;
    };

    client.Setup(GetConfig());//载入配置
    client.Connect();//连接
    client.Logger.Info("客户端成功连接");

    Console.WriteLine("输入任意内容，回车发送");
    while (true)
    {
        client.Send(Console.ReadLine());
    }
}


static TouchSocketConfig GetConfig()
{
    return new TouchSocketConfig()
            .SetRemoteIPHost(new IPHost("127.0.0.1:7789"))
            .ConfigurePlugins(a =>
            {
                a.UseReconnection()
                .SetTick(TimeSpan.FromSeconds(1))
                .UsePolling();
            })
            .ConfigureContainer(a =>
            {
                a.AddConsoleLogger();//添加一个日志注入
            });
}